using NCrontab;

namespace DK.Utils.Schedule;


public class ScheduledTask(string cron, Action<TimerTaskEventArgs> taskAction) : TimerTask(1000)
{
    private readonly CrontabSchedule _schedule = CrontabSchedule.Parse(cron, new CrontabSchedule.ParseOptions()
    {
        IncludingSeconds = cron.Split(' ').Length == 6
    });

    protected override void PollerExecute(TimerTaskEventArgs args)
    {
        DateTimeOffset nextExecuteTime = _schedule.GetNextOccurrence(DateTime.UtcNow);
        if (nextExecuteTime.ToUnixTimeSeconds() <= DateTimeOffset.UtcNow.AddSeconds(1).ToUnixTimeSeconds())
        {
            taskAction(Args);
        }
    }
    
}